package cnpm02.j2ee.group3.logic.dao.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;

import cnpm02.j2ee.group3.logic.dao.generic.AbstractEntityDaoImpl;
import cnpm02.j2ee.group3.model.City;
import cnpm02.j2ee.group3.model.FlightLine;

@Stateless
@Name("flightLineDao")
@AutoCreate
public class FlightLineDaoImpl extends AbstractEntityDaoImpl<FlightLine> implements
		FlightLineDao {

	@SuppressWarnings("unchecked")
	public List<FlightLine> selectAll() {
		
		Query query = getEntityManager().createQuery(SELECT_ALL_QUERY);
		return query.getResultList();
	}

	@Override
	public String delete(final FlightLine entity){
		if (entity != null) {
			FlightLine fl = entity.getReturnFlight();
			entity.setReturnFlight(null);
			getEntityManager().persist(entity);
			if (fl != null) {
				getEntityManager().remove(fl);
			}
			getEntityManager().remove(entity);
		}
		return "success";
	}

	public FlightLine selectFlightLineByFromAndTo(City from, City to) {
		FlightLine result;
		Query query = getEntityManager().createQuery(SELECT_FLIGHT_LINE_BY_FROM_AND_TO);
		query.setParameter("from", from);
		query.setParameter("to", to);
		try {
			result = (FlightLine) query.getSingleResult();
		} catch (NoResultException e) {
			result = null;
		}
		
		return result;
	}

}
